import mqtt from 'mqtt'

/**
 * 连接客户端
 * @param data
 *  protocol: "ws",  // 协议
 *  host: "xxx",
 *  port: "8083",
 *  endpoint: "/mqtt",
 *  clientId: "emqx_vue_client" + Math.random().toString().substring(2,8),
 *  username: "admin",
 *  password: "admin",
 *  keepalive: 30, // 心跳间隔(秒)
 *  connectTimeout: 4000, // 连接超时时间
 *  reconnectPeriod: 4000, // 重连间隔(毫秒)
 * @returns {MqttClient|null}
 */
function createConnection(data) {
  console.log('data:', data);
  try {
    const {protocol, host, port, endpoint, ...options} = data;
    const connectionUrl = `${protocol}://${host}:${port}${endpoint}`;
    console.log('connectionUrl:', connectionUrl);
    console.log('options:', options);
    return mqtt.connect(connectionUrl, options);
  } catch (err) {
    console.error(err);
    return null;
  }
}

/**
 * 断开客户端连接
 * @param client
 */
function closeConnection(client) {
  try {
    client.end(false, () => {
      console.log("客户端连接断开")
    });
    return true;
  } catch (err) {
    return false;
  }
}

/**
 * 订阅主题
 * @param client
 * @param data
 * @returns {Promise<unknown>}
 */
function subTopic(client, data) {
  return new Promise((resolve) => {
    try {
      const {topic, qos} = data;
      // 注意：Qos必须是数字
      client.subscribe(topic, {qos}, (error) => {
        if (error) {
          console.error("主题订阅失败", error);
          resolve(false);
        }
        resolve(true);
      })
    } catch (error) {
      console.error("主题订阅失败", error);
      resolve(false);
    }
  })
}

/**
 * 取消订阅
 * @param client
 * @param data
 * @returns {Promise<unknown>}
 */
function closeSub(client, data) {
  return new Promise((resolve) => {
    try {
      const {topic, qos} = data;
      // 注意：Qos必须是数字
      client.unsubscribe(topic, {qos}, (error) => {
        if (error) {
          console.error("取消订阅失败", error);
          resolve(false);
        }
        resolve(true);
      })
    } catch (error) {
      console.error("取消订阅失败", error);
      resolve(false);
    }
  })
}

/**
 * 消息发布
 * @param client
 * @param data
 * @returns {Promise<unknown>}
 */
function pubMessage(client, data) {
  return new Promise((resolve) => {
    try {
      const {topic, qos, payload} = data;
      // 注意：Qos必须是数字
      client.publish(topic, payload, {qos}, (error) => {
        if (error) {
          console.error("消息发布失败", error);
          resolve(false);
        }
        resolve(true);
      })
    } catch (error) {
      console.error("消息发布失败", error);
      resolve(false);
    }
  })
}

const MqttUtils = {createConnection, closeConnection, subTopic, closeSub, pubMessage}
export default MqttUtils;
